package cn.home.bootstrap.publishsubscribe.topic;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 *  接收端和场景4的区别：
 * 1、exchange的type为topic
 * 2、接收消息的routing key不是固定的单词，而是匹配字符串。
 */
@Slf4j
public class ReceiveLogsTopic {
  private final static String IP = "127.0.0.1";
  private final static int  PORT = 5672;
  private static final String EXCHANGE_NAME = "topic_logs";
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(IP);
    factory.setPort(PORT);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    //配置交换器，为topic模式
    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
    String queueName = channel.queueDeclare().getQueue();
    List<String> routeKeys = Arrays.asList("*.*.color","#.annimal");
    for (String routingKey : routeKeys) {
      //绑定指定的交换器的routingKey队列
      channel.queueBind(queueName, EXCHANGE_NAME, routingKey);
    }
    Consumer consumer = new DefaultConsumer(channel) {
      @Override
      public void handleDelivery(String consumerTag, Envelope envelope,
                                 AMQP.BasicProperties properties, byte[] body) throws IOException {
        String message = new String(body, "UTF-8");
        log.info(" [x] Received routingKey :{},message:{} ",envelope.getRoutingKey(),message);
      }
    };
    channel.basicConsume(queueName, true, consumer);
  }
}

